package com.wjjun.basemvpvm.view;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.trello.rxlifecycle2.components.support.RxFragment;
import com.wjjun.basemvpvm.BR;
import com.wjjun.basemvpvm.viewmodel.BaseViewModel;

/**
 * 数据绑定的基础fragment
 * Created by 67535 on 2018/4/28.
 */

public abstract class DataBindingFragment<VM extends BaseViewModel, VDB extends ViewDataBinding> extends RxFragment {

    private View rootView;
    protected VDB viewDataBinding;
    protected VM viewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        initBinding();
        return rootView;
    }

    protected void initBinding() {
        int rootLayoutId = getLayoutId();
        viewDataBinding = DataBindingUtil.inflate(getLayoutInflater(), rootLayoutId, null, false);
        if (viewDataBinding == null) {
            rootView = getLayoutInflater().inflate(rootLayoutId, null, false);
        } else {
            rootView = viewDataBinding.getRoot();
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewModel = initViewModel();
        bindViewModel();
    }

    /**
     * 获取布局文件id
     */
    public abstract int getLayoutId();

    /**
     * 初始化ViewModel
     */
    protected abstract VM initViewModel();


    /**
     * 绑定ViewModel
     */
    protected void bindViewModel() {
        //绑定presenter
        viewDataBinding.setVariable(BR.presenter, this);
        //绑定viewModel
        viewDataBinding.setVariable(BR.viewModel, viewModel);
    }

}
